import {query} from '../config/database.js'
import wechatPayV3 from '../utils/wechatPayV3.js'

/**
 * 创建支付订单（API V3）
 */
export async function createPayment(req, res) {
  try {
    const {order_no, openid} = req.body

    if (!order_no || !openid) {
      return res.status(400).json({
        success: false,
        error: '缺少必要参数'
      })
    }

    // 查询订单信息
    const orders = await query(
      'SELECT * FROM orders WHERE order_no = ?',
      [order_no]
    )

    if (!orders || orders.length === 0) {
      return res.status(404).json({
        success: false,
        error: '订单不存在'
      })
    }

    const order = orders[0]

    // 检查订单状态
    if (order.status !== 'pending') {
      return res.status(400).json({
        success: false,
        error: '订单状态不正确'
      })
    }

    // 查询展览信息
    const exhibitions = await query(
      'SELECT * FROM exhibitions WHERE id = ?',
      [order.exhibition_id]
    )

    if (!exhibitions || exhibitions.length === 0) {
      return res.status(404).json({
        success: false,
        error: '展览不存在'
      })
    }

    const exhibition = exhibitions[0]

    // 调用微信支付统一下单接口（V3）
    const result = await wechatPayV3.createOrder({
      description: exhibition.title,
      out_trade_no: order_no,
      total_fee: Math.round(order.total_amount * 100), // 转换为分
      openid: openid
    })

    if (!result.success) {
      // 记录支付日志
      await query(
        'INSERT INTO payment_logs (order_no, openid, amount, status, error_msg) VALUES (?, ?, ?, ?, ?)',
        [order_no, openid, order.total_amount, 'failed', result.error]
      )

      return res.status(500).json({
        success: false,
        error: result.error || '创建支付订单失败'
      })
    }

    // 生成小程序调起支付参数
    const payParams = wechatPayV3.generatePayParams(result.data.prepay_id)

    // 记录支付日志
    await query(
      'INSERT INTO payment_logs (order_no, openid, amount, status) VALUES (?, ?, ?, ?)',
      [order_no, openid, order.total_amount, 'pending']
    )

    res.json({
      success: true,
      data: payParams
    })
  } catch (error) {
    console.error('创建支付订单失败:', error)
    res.status(500).json({
      success: false,
      error: error.message || '创建支付订单失败'
    })
  }
}

/**
 * 支付回调通知（API V3）
 */
export async function paymentNotify(req, res) {
  try {
    // 验证签名（异步）
    const isValid = await wechatPayV3.verifySignature(req.headers, JSON.stringify(req.body))

    if (!isValid) {
      console.error('支付回调签名验证失败')
      return res.status(400).json({
        code: 'FAIL',
        message: '签名验证失败'
      })
    }

    const {resource} = req.body

    // 解密数据
    const data = wechatPayV3.decryptData(resource)

    if (!data) {
      console.error('解密回调数据失败')
      return res.status(400).json({
        code: 'FAIL',
        message: '解密数据失败'
      })
    }

    const {
      out_trade_no,
      transaction_id,
      trade_state,
      trade_state_desc,
      amount
    } = data

    console.log('收到支付回调:', {
      out_trade_no,
      transaction_id,
      trade_state,
      trade_state_desc
    })

    // 查询订单
    const orders = await query(
      'SELECT * FROM orders WHERE order_no = ?',
      [out_trade_no]
    )

    if (!orders || orders.length === 0) {
      console.error('订单不存在:', out_trade_no)
      return res.status(404).json({
        code: 'FAIL',
        message: '订单不存在'
      })
    }

    const order = orders[0]

    // 检查订单金额
    const orderAmount = Math.round(order.total_amount * 100)
    if (amount.total !== orderAmount) {
      console.error('订单金额不匹配:', {
        expected: orderAmount,
        actual: amount.total
      })
      return res.status(400).json({
        code: 'FAIL',
        message: '订单金额不匹配'
      })
    }

    // 更新订单状态
    if (trade_state === 'SUCCESS') {
      await query(
        'UPDATE orders SET status = ?, transaction_id = ?, paid_at = NOW() WHERE order_no = ?',
        ['paid', transaction_id, out_trade_no]
      )

      // 更新支付日志
      await query(
        'UPDATE payment_logs SET status = ?, transaction_id = ? WHERE order_no = ? AND status = ?',
        ['success', transaction_id, out_trade_no, 'pending']
      )

      console.log('订单支付成功:', out_trade_no)
    } else {
      // 更新支付日志
      await query(
        'UPDATE payment_logs SET status = ?, error_msg = ? WHERE order_no = ? AND status = ?',
        ['failed', trade_state_desc, out_trade_no, 'pending']
      )

      console.log('订单支付失败:', out_trade_no, trade_state_desc)
    }

    // 返回成功响应
    res.json({
      code: 'SUCCESS',
      message: '成功'
    })
  } catch (error) {
    console.error('处理支付回调失败:', error)
    res.status(500).json({
      code: 'FAIL',
      message: error.message || '处理失败'
    })
  }
}

/**
 * 查询支付状态（API V3）
 */
export async function queryPaymentStatus(req, res) {
  try {
    const {orderNo} = req.params

    if (!orderNo) {
      return res.status(400).json({
        success: false,
        error: '缺少订单号'
      })
    }

    // 调用微信支付查询订单接口
    const result = await wechatPayV3.queryOrder(orderNo)

    if (!result.success) {
      return res.status(500).json({
        success: false,
        error: result.error || '查询支付状态失败'
      })
    }

    res.json({
      success: true,
      data: {
        trade_state: result.data.trade_state,
        trade_state_desc: result.data.trade_state_desc
      }
    })
  } catch (error) {
    console.error('查询支付状态失败:', error)
    res.status(500).json({
      success: false,
      error: error.message || '查询支付状态失败'
    })
  }
}

/**
 * 申请退款（API V3）
 */
export async function refundPayment(req, res) {
  try {
    const {order_no, refund_reason} = req.body

    if (!order_no) {
      return res.status(400).json({
        success: false,
        error: '缺少订单号'
      })
    }

    // 查询订单信息
    const orders = await query(
      'SELECT * FROM orders WHERE order_no = ?',
      [order_no]
    )

    if (!orders || orders.length === 0) {
      return res.status(404).json({
        success: false,
        error: '订单不存在'
      })
    }

    const order = orders[0]

    // 检查订单状态
    if (order.status !== 'paid') {
      return res.status(400).json({
        success: false,
        error: '订单状态不正确，只能退款已支付的订单'
      })
    }

    // 生成退款单号
    const refundNo = 'RF' + Date.now()

    // 调用微信支付退款接口
    const result = await wechatPayV3.refund({
      out_trade_no: order_no,
      out_refund_no: refundNo,
      total_fee: Math.round(order.total_amount * 100),
      refund_fee: Math.round(order.total_amount * 100),
      reason: refund_reason || '用户申请退款'
    })

    if (!result.success) {
      return res.status(500).json({
        success: false,
        error: result.error || '申请退款失败'
      })
    }

    // 更新订单状态
    await query(
      'UPDATE orders SET status = ?, refund_no = ?, refunded_at = NOW() WHERE order_no = ?',
      ['refunded', refundNo, order_no]
    )

    res.json({
      success: true,
      data: {
        refund_no: refundNo
      }
    })
  } catch (error) {
    console.error('申请退款失败:', error)
    res.status(500).json({
      success: false,
      error: error.message || '申请退款失败'
    })
  }
}

/**
 * 下载平台证书
 */
export async function downloadCertificates(req, res) {
  try {
    const result = await wechatPayV3.downloadCertificates()

    if (!result.success) {
      return res.status(500).json({
        success: false,
        error: result.error || '下载平台证书失败'
      })
    }

    res.json({
      success: true,
      message: `成功下载 ${result.count} 个平台证书`
    })
  } catch (error) {
    console.error('下载平台证书失败:', error)
    res.status(500).json({
      success: false,
      error: error.message || '下载平台证书失败'
    })
  }
}

/**
 * 获取证书列表
 */
export async function getCertificates(req, res) {
  try {
    const certificates = Array.from(wechatPayV3.platformCertificates.keys())

    res.json({
      success: true,
      data: {
        certificates,
        lastUpdate: wechatPayV3.certificatesLastUpdate,
        count: certificates.length
      }
    })
  } catch (error) {
    console.error('获取证书列表失败:', error)
    res.status(500).json({
      success: false,
      error: error.message || '获取证书列表失败'
    })
  }
}

